package net.ikenna.yadet.springjdbc;

import net.ikenna.yadet.core.*;
import net.ikenna.yadet.core.data.*;
import org.apache.log4j.*;
import org.springframework.jdbc.core.*;

public class SpringJdbcTemplateInserter implements Inserter {
    private JdbcTemplate jdbcTemplate;
    private Logger logger = Logger.getLogger(SpringJdbcTemplateInserter.class);

    public SpringJdbcTemplateInserter(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void insertIntoNewTable(RowSet rowSet) {
        dropTableIfExists();
        createTable();
        insertNewData(rowSet);
    }

    private void insertNewData(RowSet rowSet) {
        String sql = "INSERT INTO cleaned_cds (title, year, artist, id) VALUES (?, ?, ?, ?)";
        logger.info("[Insertion SQL] %s " +  sql);
        int rowsUpdated = 0;
        for (Row row : rowSet.getRows()) {
            Object[] arguments = new Object[]{row.getColumnValue("title"), row.getColumnValue("year"), row.getColumnValue("artist"), row.getColumnValue("id")};
            rowsUpdated +=  jdbcTemplate.update(sql, arguments);
        }
        logger.info("[Rows updated]" + rowsUpdated);
    }

    private void createTable() {
        final String createTableSql = "CREATE TABLE cleaned_cds (id INTEGER, title VARCHAR(100), " +
                "artist VARCHAR(100), year VARCHAR(100))";
        logger.info("[Creating table]" + createTableSql);
        jdbcTemplate.execute(createTableSql);
    }

    private void dropTableIfExists() {
        String dropTable = "DROP TABLE IF EXISTS cleaned_cds";
        logger.info("[Dropping table]" + dropTable);
        jdbcTemplate.execute(dropTable);
    }
}